/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.rpc.service.impl  
 */
package com.apache.rpc.service.impl;

import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

import org.apache.log4j.Logger;

import com.apache.api.api.ApiService;
import com.apache.api.api.SystemService;
import com.apache.api.entity.BaseEntity;
import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.constant.Validator;
import com.apache.exception.BusinessException;
import com.apache.rpc.server.impl.ProtocolAdapter;
import com.apache.rpc.util.DesUtils;
import com.apache.rpc.util.JsonEntityParese;
import com.apache.rpc.util.XMLMapParse;

/**
 * description:  webservice访问路径/service/ApiService?wsdl
 * @author Hou Dayu 创建时间：2014-10-31  
 * @Copyright(c)2014:
 */
@WebService
@SOAPBinding(style = Style.RPC)
public class SystemEncryptionServiceImpl implements SystemService {
	private Logger log = Logger.getLogger(ProtocolAdapter.class);
	private List<PluginConnector> plugins;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.apache.api.api.SystemService#doService(java.lang.String, com.apache.api.api.SystemService.ParamType)  
	 */
	@SuppressWarnings({ "unchecked" })
	public String doService(String params, ParamType type) {

		ParamsVo<BaseEntity> pvo = new ParamsVo<BaseEntity>();
		params = DesUtils.getInstance().decrypt(params);
		if (!params.startsWith("<?xml")) {
			params = XMLMapParse.instance().jsonToXMl(params);
		}
		pvo.setKey(params);
		String result = "";
		if (Validator.isEmpty(plugins))
			return result;
		try {
			ParamsVo<BaseEntity> vo = new ParamsVo<BaseEntity>();
			for (PluginConnector plugin : plugins) {
				plugin.execute(pvo);
			}
			Map<String, Object> headMap = (Map<String, Object>) pvo.getParams("headMap");
			Map<String, Object> bodyMap = (Map<String, Object>) pvo.getParams("bodyMap");
			vo.setMethodKey(headMap.get("MethodCode").toString());
			vo.setParams(bodyMap);
			ApiService service = (ApiService) SpringContextLoader.getBean(headMap.get("BeanId").toString());
			ResultEntity entity = service.doService(vo);

			if (Validator.isEmpty(entity))
				return "";
			switch (type) {
			case JSON:
				result = JsonEntityParese.instance().beanToJson(entity);
				break;
			case XML:
				result = JsonEntityParese.instance().toXml(entity, entity.getEntity());
				break;
			}
			result = DesUtils.getInstance().encrypt(result);//对返回值加密
		} catch (Exception e) {
			log.error(e);
			throw new BusinessException("执行方法出错", e);
		}
		return result;
	}

	public void setPlugins(List<PluginConnector> plugins) {
		this.plugins = plugins;
	}
}
